<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { showConfirmDialog, showSuccessToast, showToast } from 'vant';
import { zhiya } from '@/common/api/pledgeReward';

defineProps<{
  info: any;
}>();

const emit = defineEmits<{
  (e: 'refresh'): void;
}>();

const show = ref(false);
const zhiyaLoading = ref(false);
const zrNum = ref(''); // 转入数量
const errorOption = reactive({
  error: false,
  errorMessage: '',
});

watch(zrNum, () => {
  if (parseFloat(zrNum.value) < 0) {
    errorOption.error = true;
    errorOption.errorMessage = '转入数量不能小于零';
  } else if (zrNum.value.indexOf('.') > -1) {
    errorOption.error = true;
    errorOption.errorMessage = '转入数量不能为小数';
  } else {
    errorOption.error = false;
    errorOption.errorMessage = '';
  }
});

const close = () => {
  show.value = false;
  zrNum.value = '';
};

// 质押转入
const handleZhiya = async () => {
  if (!zrNum.value) {
    return showToast('转入数量不能为空');
  }
  try {
    await showConfirmDialog({
      title: '提示',
      message: `确认转入${zrNum.value}数量吗？`,
    });
    zhiyaLoading.value = true;
    await zhiya({ price: parseInt(zrNum.value) });
    showSuccessToast('转入成功');
    emit('refresh');
    close();
  } catch {
    /** empty */
  } finally {
    zhiyaLoading.value = false;
  }
};

defineExpose({
  open() {
    show.value = true;
  },
});
</script>
<template>
  <div class="zhiyaDialog">
    <van-popup v-model:show="show" :close-on-click-overlay="false" :style="{ width: '85vw', borderRadius: '10px' }">
      <div class="bg-white mx-3 rounded-lg mt-1 px-3 pb-3">
        <div class="pt-4 mb-3 flex justify-between">
          <span class="font-medium">转入数量</span>
          <span class="text-xs text-[#999999]" @click="close">取消</span>
        </div>
        <div class="border-b border-[#e5e5e5]">
          <van-field
            class="!px-0"
            v-model="zrNum"
            :error="errorOption.error"
            :error-message="errorOption.errorMessage"
            size="large"
            type="number"
            placeholder="请输入转入数量"
          />
        </div>
        <div class="text-xs text-[#999999] mt-1">{{ info?.seg2?.tip1 || '-' }}</div>
        <div class="mt-8 mb-2">
          <van-button
            type="primary"
            block
            round
            color="#EC2D69"
            :loading="zhiyaLoading"
            :disabled="errorOption.error || !zrNum"
            @click="handleZhiya"
          >
            立即转入
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
